package com.xiaobing.common.tree;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: xiaobingback
 * @author: xulk
 * @create: 2024-07-22 17:47
 */
public class ToTreeUtils  {


    // 将集合转换为树结构
    public static <T extends TreeNode> List<T> buildTree(List<T> nodes) {
        Map<Long, T> nodeMap = new HashMap<>();
        for (T node : nodes) {
            nodeMap.put(node.getId(), node);
        }
        List<T> treeNodes = new ArrayList<>();
        for (T node : nodes) {
            T parent = nodeMap.get(node.getParentId());
            if (parent != null) {
                if (parent.getChildren() == null) {
                    parent.setChildren(new ArrayList<>());
                }
                parent.getChildren().add(node);
            } else {
                treeNodes.add(node);
            }
        }
        return treeNodes;
    }



}

